<?php

declare(strict_types=1);

namespace App\Ai\Job;

use App\Ai\Model\AiKnowledgeFile;
use GuzzleHttp\Client;
use Hyperf\AsyncQueue\Job;
use Hyperf\DbConnection\Db;
use TheoGibbons\ChromaPHP\ChromaDBClient;

class AiKnowledgeJob extends Job
{
    public function __construct(public int $file_id)
    {
    }

    public function handle(): void
    {
        $path = Db::table('system_uploadfile')->where(['id' => $this->file_id])->value('url');
        $path = BASE_PATH . '/public/' . env('UPLOAD_PATH', 'uploadfile') . $path;
        $tenantName = env('CHROMADB_TENANT');
        $databaseName = env('CHROMADB_DATABASE');
        $collection_db = env('CHROMADB_DB');
        $chroma = ChromaDBClient::connect([
            'host' => env('CHROMADB_HOST'),
            'port' => env('CHROMADB_PORT'),
//            'authToken'=>env(),
        ]);
        $client = new Client();
        $response = $client->post(env('SERVER_AI_EMBED') . '/embed', [
            'json' => ['text' => file_get_contents($path)]
        ]);
        $data = json_decode($response->getBody()->getContents(), true);
        $ids = [];
        foreach ($data['embeddings'] as $i => $v) $ids[] = 'id' . $i;
        $chroma->addToCollection($tenantName, $databaseName, $collection_db, [
            'ids' => $ids,
            'embeddings' => $data['embeddings'],
            'documents' => $data['sentences'],
        ]);
        AiKnowledgeFile::query()->where(['file_id' => $this->file_id])->update(['status' => 1]);
    }
}